import Flutter
import UIKit

public class SwiftMicrocosmLogPlugin: NSObject, FlutterPlugin {

    static let shared = SwiftMicrocosmLogPlugin()
    
    private override init() {}
    
    public override func copy() -> Any {
        return self
    }
        
    public override func mutableCopy() -> Any {
        return self
    }
    
    var channel = nil as FlutterMethodChannel?
    
    var flutterConnect = false
    
    var connectFlutterListener: (() -> Void)? = nil

    public static func register(with registrar: FlutterPluginRegistrar) {
        let instance = SwiftMicrocosmLogPlugin.shared
        instance.channel = FlutterMethodChannel(name: "microcosm_log", binaryMessenger: registrar.messenger())
        registrar.addMethodCallDelegate(instance, channel: instance.channel!)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if (call.method == "onConnected") {
            flutterConnect = true
            connectFlutterListener?()
        } else {
            result(FlutterMethodNotImplemented)
        }
    }

    
    public func sendMethodToFlutter(method: String, arguments: Any?) {
        if (Thread.current.isMainThread) {
            channel?.invokeMethod(method, arguments: arguments)
        } else {
            DispatchQueue.main.async { [self] in
                channel?.invokeMethod(method, arguments: arguments)
            }
        }
    }
}
